const Mock = require('@/utils/request/mock.js');
const mockConfig = require("@/utils/request/mockconfig.js")
const urlConfig = require("@/utils/request/urlconfig.js")
const config = require("@/utils/config.js")
import Vue from 'vue'

var http = function (url, params, successfn, failfn, method, header = {}, needlogin = false, showloading = true) {

	var _url = url
	// var pages = getCurrentPages()
	// var page = pages[pages.length - 1]

	// url为必传参数
	if (!_url) {
		try {} catch (error) {
			uni.showToast({
				title: '当前请求 url 为空！！',
				duration: 1500,
				icon: 'none'
			});
		}
		return console.error('当前请求 url 为空！！')
	}

	let withToken = {
		'Content-Type': 'application/json; charset=utf-8',
		'authorization': uni.$_getToken()
	}
	var _header = header

	// 判断有没有传入初始参数
	if (JSON.stringify(_header) == '{}') {
		_header = withToken
	}

	// 拆分url: 接口|参数
	var aryUrl = url.split('|')

	// 判断类型
	// aryUrl.length > 1 即 带参数
	if (aryUrl.length > 1) {
		_url = aryUrl[0]
	}
	// 整理地址格式
	if (urlConfig[_url]) {
		var _hostUrl = uni.$_changeHost(urlConfig[_url], config)
	} else {
		var _hostUrl = _url
	}
	// Mock 数据
	// 当配置项里没有配置api时 或者 开启Mock模式时
	// if (!urlConfig[_url] || _hostUrl.indexOf('[Mock]') != -1) {
	// 	if (!urlConfig[_url]) {
	// 		try {} catch (error) {
	// 			uni.showToast({
	// 				title: '(' + _url + ')没有配置API，将使用 Mock...',
	// 				duration: 1500,
	// 				icon: 'none'
	// 			});
	// 		}
	// 	} else {
	// 		try {} catch (error) {
	// 			uni.showToast({
	// 				title: '正在使用 Mock...',
	// 				duration: 1500,
	// 				icon: 'none'
	// 			});
	// 		}
	// 	}
	// 	try {
	// 		var mockData = Mock.mock(mockConfig[_url])
	// 	} catch (e) {
	// 		//TODO handle the exception
	// 		console.error('(' + _url + ') Mock 配置文件出错')
	// 	}

	// 	var def = {
	// 		data: '',
	// 		code: 1,
	// 		message: "mock数据"
	// 	}
	// 	var res = Object.assign(def, mockData)

	// 	console.log('(' + _url + ')正在使用 Mock：')
	// 	successfn ? successfn(res) : console.error("success: function(e) is undefined")
	// } else {
		
	// }
	// console.log('正在发送请求...')
	if (showloading) {
		// uni.showLoading({
		// 	title: '加载中...'
		// })
	}
	
	// 判断类型
	// aryUrl.length > 1 即 带参数
	if (aryUrl.length > 1) {
		_hostUrl += aryUrl[1]
	}
	
	uni.request({
		url: _hostUrl,
		data: params,
		header: _header,
		method: method,
		success: function (res) {
			let res1 = res.data
			switch (res1.code) {
				case 0:
					successfn ? successfn(res1) : console.error("success: function(e) is undefined")
					break;
					// 401-清除登录信息
				case 2:
					successfn ? successfn(res1) : console.error("success: function(e) is undefined")
					break;
				case 611:
					uni.$_removeToken();
					// uni.showToast({
					// 	title: '请先登录',
					// 	duration: 1500,
					// 	icon: 'none'
					// });
					// uni.showModal({
					// 	title: '提示',
					// 	content: '登录过期或未登录！',
					// 	confirmText:'去登录',
					// 	cancelText:'取消',
					// 	success: function (res) {
					// 		if (res.confirm) {
					// 			uni.$_removeToken();
					// 			uni.$_navFn("to", "/pages/login/login");
					// 		} else if (res.cancel) {
								
					// 		}
					// 	}
					// })
					// uni.$_publicModal('登录过期或未登录！', function () {
					//     uni.$_removeToken();
					// 	uni.$_navFn("too", "/pages/login/login");
					// },function(){
					// 	// uni.navigateBack()
						
					// },'去登录')
					// if (!Vue.prototype.$isLogged) {
					// 	Vue.prototype.$isLogged = true;
					// 	let url = "/pages/login/login";
					// 	uni.$_navFn("to", url);
					// }else{
					// 	uni.$_removeToken();
					// 	//Vue.prototype.$isLogged = false
					// 	failfn ? failfn(res1) : console.error("success: function(e) is undefined")
					// }
					break;
				default:
					try {} catch (error) {
						uni.showToast({
							title: '系统开小差了...',
							duration: 1500,
							icon: 'none'
						});
					}
					// console.error("请求返回错误码(" + getCurrentPages()[getCurrentPages().length - 1].route + "[" + _url + '/' + _hostUrl + "]): " + res1.code + res1.msg)
					console.error("请求返回错误码(" + "[" + _url + '/' + _hostUrl + "]): " + res1 + res1.msg)
					failfn ? failfn(res1) : console.error("success: function(e) is undefined")
					break;
			}
	
			if (showloading) {
				setTimeout(() => {
					uni.hideLoading()
				}, 300);
			}
		},
		fail: function (err) {
			failfn("fail")
			try {} catch (error) {
				uni.showToast({
					title: '系统出错了...',
					duration: 1500,
					icon: 'none'
				});
			}
			if (showloading) {
				setTimeout(() => {
					uni.hideLoading()
				}, 300);
			}
		}
	})
}

var request = {
	get: function ({
		method = 'GET',
		url = '',
		params = '',
		success = function (e) {},
		fail = function (e) {},
		header = {},
		that,
		needlogin = false
	}) {
		that.$nextTick(() => {
			http(url, params, success, fail, method, header, needlogin)
		})
	},
	post: function ({
		method = 'POST',
		url = '',
		params = '',
		success = function (e) {},
		fail = function (e) {},
		header = {},
		that,
		needlogin = false
	}) {
		that.$nextTick(() => {
			http(url, params, success, fail, method, header, needlogin)
		})
	},
	// 不带 showloading
	httpGet: function ({
		method = 'GET',
		url = '',
		params = '',
		success = function (e) {},
		fail = function (e) {},
		header = {},
		showloading = false,
		that,
		needlogin = false
	}) {
		that.$nextTick(() => {
			http(url, params, success, fail, method, header, needlogin, showloading)
		})
	},
	httpPost: function ({
		method = 'POST',
		url = '',
		params = '',
		success = function (e) {},
		fail = function (e) {},
		header = {},
		showloading = false,
		that,
		needlogin = false
	}) {
		that.$nextTick(() => {
			http(url, params, success, fail, method, header, needlogin, showloading)
		})
	}
}

module.exports = request